<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\Assets;
use app\common\model\OrderVideo;
use app\common\model\UserLevelVideo;
use app\common\model\UserVideoComment;
use app\common\model\UserVideoHit;
use app\common\model\BusinessVideo as VideoModel;
use app\common\model\Account;
use app\common\model\VideoCate;
use app\common\tool\Result;
use think\Response;

class UserVideo extends Base
{
    /**
     * 视频会员等级
     */
    public function userLevel(): Response
    {
        $level = $this->user->level_video_id;
        $result['level_video_id'] = $level;

        return Result::success('success', $result);
    }

    /**
     * 分类列表
     * @return Response
     */
    public function cateList() :Response
    {
        try {
            $list = VideoCate::where('is_del', 0)->field('id,title')->select();

            $result = ['code'=>1, 'msg'=>'success', 'data'=>$list];
            return Result::fastReturn($result);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * 视频列表
     */
    public function index(): Response
    {
        $map['is_del'] = 0;
        $map['show'] = 1;
        $map['status'] = 2;

        $param = $this->request->param();
        if(!empty($param['cate_id'])) $map['cate_id'] = $param['cate_id'];

        $record = VideoModel::accountRecord();

        $sql = VideoModel::with(['comment'])->where($map);
        if(!empty($param['keyword'])) $sql->whereLike('tag|introduce', '%'.$param['keyword'].'%');
        $list = $sql->field('id,cover,introduce,link,tag,total_seconds,total_hit,total_comment,total_view,total_share,product_id,cate_id')
            ->append(['linkDomain'])
            ->orderRaw('rand()')
            ->paginate($this->getLimit())->each(function ($item) use ($record) {
                $item->is_hit = UserVideoHit::where(['uid' => $this->user->id, 'video_id' => $item->id])->count() ? 1 : 0;
                $item->red_coin = Assets::where('uid', $this->user->id)->value('red_coin');
                $item->record = $record;
            });

        return Result::success('success', $list->items());
    }

    /**
     * 视频详情
     */
    public function info(): Response
    {
        $id = $this->request->param('id', 0);

        $info = VideoModel::info($id, $this->user);
        $all_ids = VideoModel::where('id', '<>', $id)->where(['is_del' => 0, 'status' => 2])->column('id', 'id');
        $last = $next = null;
        if($all_ids){
            if(count($all_ids) < 2){
                $ln[0] = $ln[1] = array_values($all_ids)[0];
            }else{
                $ln = array_rand($all_ids, 2);
            }

            if(isset($ln[0])) {
                $last_id = $ln[0];
                $last = VideoModel::info($last_id, $this->user);
            }

            if(isset($ln[1])) {
                $next_id = $ln[1];
                $next = VideoModel::info($next_id, $this->user);
            }
        }
        if(!$last) $last = $info;
        if(!$next) $next = $info;

        $record = VideoModel::accountRecord();

        $data = [
            'current' => $info,
            'last'    => $last,
            'next'    => $next,
            'record'  => $record
        ];

        return Result::fastReturn(['code' => 1, 'msg' => 'success', 'data' => $data]);
    }

    /**
     * 视频点赞
     */
    public function hit(): Response
    {
        try {
            $id = $this->request->param('id', 0);
            return Result::fastReturn(UserVideoHit::hit($id, $this->user->id));
        } catch (\Exception $e) {
            return Result::fail('加载失败，服务器错误！');
        }
    }

    /**
     * 视频评论
     */
    public function comment(): Response
    {
        try {
            $param = $this->request->post();
            $this->validate($param, 'UserVideoComment');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }

        return Result::fastReturn(UserVideoComment::add($param, $this->user->id));
    }

    /**
     * 视频会员等级
     */
    public function level(): Response
    {
        $level = UserLevelVideo::field('id,title,take_amount')->select();

        $pay_way = [
            [
                "title" => "支付宝",
                "pay_way" => "alipay",
                "is_pay_password" => 0
            ],
            [
                "title" => "微信",
                "pay_way" => "wechat",
                "is_pay_password" => 0
            ],
            [
                "title" => "VIP积分",
                "pay_way" => "vip_integ",
                "is_pay_password" => 1
            ],
            [
                "title" => "爱豆",
                "pay_way" => "love_bean",
                "is_pay_password" => 1
            ],
            [
                "title" => "链豆",
                "pay_way" => "chain_bean",
                "is_pay_password" => 1
            ]
        ];

        $result = [
            'level' => $level,
            'pay_way' => $pay_way
        ];
        return Result::success('success', $result);
    }

    /**
     * 视频会员购买
     */
    public function buy(): Response
    {
        //return Result::fail('通道已关闭');
        try {
            $param = $this->request->post();
            $this->validate($param, 'OrderVideo');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
        return Result::fastReturn(OrderVideo::payment($param, $this->user));
    }

    /**
     * 视频会员充值记录
     */
    public function buyRecord(): Response
    {
        $map['is_del'] = 0;
        $map['pay_state'] = 1;
        $map['uid'] = $this->user->id;
        $list = OrderVideo::getPageList($map, 'id,sn,uid,real_amount,create_time,pay_time', $this->getPage(), $this->getLimit(), false, ['user']);

        return Result::fastReturn($list);
    }

    /**
     * 看视频得红包币
     */
    public function getRedCoin(): Response
    {
        return Result::fastReturn(OrderVideo::getRedCoin($this->user, $this->system['video_red_coin'], $this->request->param('type', 1)));
    }

    /**
     * 视频奖励记录
     */
    public function redCoinRecord(): Response
    {
        $map['type'] = 'red_coin';
        $map['fx'] = '+';
        $list = Account::getPageList($map, 'id,uid,intro,amount,create_time', $this->getPage(), $this->getLimit(), false, ['user']);

        return Result::fastReturn($list);
    }

    /**
     * 视频分享次数更新
     * @param $id
     * @return Response
     */
    public function upShare($id): Response
    {
        try {
            VideoModel::where('id', $id)->inc('total_share')->update();
            return Result::success();
        } catch (\Exception $e) {
            return Result::fail('服务器错误');
        }
    }

}
